#include"../Common/Net.hpp"
#include"../Common/Message.hpp"
#include "../Common/Dispatcher.hpp"
#include "../Server/Rpc_Router.hpp"

// using ConnectionCallback = std::function<void(const BaseConnection::ptr &conn)>;
// using MessageCallback = std::function<void(const BaseConnection::ptr &conn, const BaseMessage::ptr &buf)>;
// using CloseCallback = std::function<void(const BaseConnection::ptr &conn)>; 


void OnRpcMessage(const zgwrpc::BaseConnection::ptr &conn, const zgwrpc::RpcRequest::ptr &req)
{
    Json::Value params=req->params(), result;
    int num1 = params["num1"].asInt();
    int num2 = params["num2"].asInt();
    result["sum"] = num1 + num2;
    zgwrpc::RpcResponse::ptr res = zgwrpc::MessageFactory::create<zgwrpc::RpcResponse>();
    res->setId(req->rid());
    
    res->setResult(result);
    res->setRCode(zgwrpc::RCode::RCODE_OK);
    res->setMType(zgwrpc::MType::RSP_RPC);
    conn->send(res);
}

bool Add(const Json::Value &params, Json::Value &result)
{
    int num1 = params["num1"].asInt();
    int num2 = params["num2"].asInt();
    result["sum"] = num1 + num2;
    return true;
}

bool Gamer(const Json::Value &params, Json::Value &result)
{
    string game=params["game"].asString();
    if(game=="原神")
        result["正在打开"]="原神启动";
    else if(game=="魔兽世界")
        result["正在打开"]="魔兽世界启动";
    else if( game=="第五人格")
        result["正在打开"]="第五人格启动";
    else result["正在打开"]="游戏不存在";
        return true;
}


void test1()
{
    //创建一个rpcrouter
    zgwrpc::server::Rpc_Router::ptr router=make_shared<zgwrpc::server::Rpc_Router>();
    //来一个请求描述制造类
    zgwrpc::server::ServerDescribeBuilder buiderAdd;
    buiderAdd.SetCallback(Add);
    buiderAdd.SetMthodName("Add");
    buiderAdd.SetReturnType(zgwrpc::server::VType::INTEGRAL);
    buiderAdd.SetParamsDescribe("num1", zgwrpc::server::VType::INTEGRAL);
    buiderAdd.SetParamsDescribe("num2", zgwrpc::server::VType::INTEGRAL);

    zgwrpc::server::ServerDescribeBuilder buiderGame;
    buiderGame.SetCallback(Gamer);
    buiderGame.SetMthodName("Game");
    buiderGame.SetReturnType(zgwrpc::server::VType::STRING);
    buiderGame.SetParamsDescribe("game", zgwrpc::server::VType::STRING);

    //注册请求描述
    router->Register(buiderAdd.Build());
    router->Register(buiderGame.Build());


    zgwrpc::BaseServer::ptr server=zgwrpc::ServerFactory::create(8888);

    zgwrpc::Dispatcher::ptr dispatcher = zgwrpc::DispatcherFactory::create();
    dispatcher->registerHandler<zgwrpc::RpcRequest>(zgwrpc::MType::REQ_RPC, std::bind(&zgwrpc::server::Rpc_Router::OnRpcRequest,
                                    router, std::placeholders::_1, std::placeholders::_2));


    server->setMessageCallback(std::bind(&zgwrpc::Dispatcher::dispatch, dispatcher, std::placeholders::_1, std::placeholders::_2));




    server->start();
}

int main()
{
    test1();
    return 0;
}